<?php

declare(strict_types=1);
/*
 * @Description: 通用service类
 * @Author: QianLong
 * @Date: 2019-10-13 12:39:05
 * @LastEditors    : QianLong
 * @LastEditTime   : 2024-05-10 17:52:58
 */

namespace App\Service;

use App\Common\RedisCache;
use Yurun\Util\HttpRequest;
use Hyperf\Di\Annotation\Inject;
use Ip2Region;
class Common
{
    #[Inject]
    protected HttpRequest $http;

    #[Inject]
    protected RedisCache $redisCache;

    public function isJson($data)
    {
        return $data === json_encode(json_decode($data,true));
    }
    public function isIPv4($ip)
    {
        return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
    }
    public function encryptDevKEY($plainText)
    {
        return openssl_encrypt($plainText, 'AES-128-CTR', 'dev_ly_168', 0, '1234567891011121');
    }
    public function decryptDevKEY($cipherText)
    {
        return openssl_decrypt($cipherText, 'AES-128-CTR', 'dev_ly_168', 0, '1234567891011121');
    }
    public function mongodbIndexCreate($collection,$name,$indexFields){
        // 1=升序，-1=降序
        $indexes = $collection->listIndexes();
        $indexExists = false;
        foreach ($indexes as $index) {
            if ($index->getName() == $name) {
                $indexExists = true;
                break;
            }
        }
        unset($indexes,$index);
        if (!$indexExists) {
            $collection->createIndex($indexFields, ['background' => true, 'sparse' => true, 'name' => $name]);
        }
        unset($indexExists,$name, $collection,$name, $indexFields);
    }
    public function is_base64_encoded($str)
    {
        if (base64_decode($str, true) === false) {
            unset($str);
            return false;
        } else {
            unset($str);
            return true;
        }
    }
    public static function listToTreeMulti($list, $root = 0, $pk = 'id', $pid = 'parentId', $child = 'child', $path = 'path', $lastpath = '')
    {
        $tree = array();
        foreach ($list as $v) {
            if ($v[$pid] == $root) {
                if (isset($v['filePath'])) {
                    $v[$path] = $lastpath . '/' . $v['filePath'];
                } else {
                    $v[$path] = '';
                }
                $v[$child] = self::listToTreeMulti($list, $v[$pk], $pk, $pid, $child, $path, $v[$path]);
                $tree[]    = $v;
            }
        }
        unset($list, $root, $pk, $pid, $child, $path, $lastpath);
        return $tree;
    }
    public function ip2Region($ip)
    {
        if (!$this->isIPv4($ip)) {
            return '';
        }
        $ip2region = new Ip2Region();
        $ipInfo = $ip2region->btreeSearch($ip);
        $regionStr = '';
        if (isset($ipInfo['region'])) {
            $region = explode('|', $ipInfo['region']);
            foreach ($region as $key => $vo) {
                if (!empty($vo)) {
                    if (count($region) == $key + 1) {
                        $regionStr .= ' (' . $vo . ')';
                    } else {
                        $regionStr .= $vo;
                    }
                }
            }  
        }
        return $regionStr;
    }
    public function emailSend($postData, $serverInfo)
    {
        $postData['dev_key'] = (isset($postData['dev_key']) && !empty($postData['dev_key']))? $postData['dev_key']:'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
        $postData['es_id'] = (isset($postData['es_id']) && !empty($postData['es_id'])) ? $postData['es_id'] : 'ES-4817058244179833';
        $postData['sign'] = $this->generateSignature($postData, $serverInfo['server_secret'])['sign'];
        $response = $this->http->post('https://21ds.cn/email/send', $postData);
        return json_decode($response->body(), true);
    }
    public function getMiniAppUrlLink($ma_id, $page ='', $query = '')
    {
        $postData['ma_id'] = $ma_id;
        $postData['page'] = $page;
        $postData['query'] = $query;
        $serverInfo = $this->redisCache->getMxAppInfo($ma_id);
        $userInfo = $this->redisCache->getUserSettingByUid($serverInfo['uid']);
        $postData['dev_key'] = $userInfo['dev_key'];
        $postData['sign'] = $this->generateSignature($postData, $serverInfo['server_secret'])['sign'];
        $response = $this->http->get('https://21ds.cn/mp_miniapp/getUrlLink', $postData);
        return json_decode($response->body(), true);
    }
    public function smsSend($postData, $serverInfo)
    {
        $postData['dev_key'] = (isset($postData['dev_key']) && !empty($postData['dev_key'])) ? $postData['dev_key'] : 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
        $postData['ss_id'] = (isset($postData['ss_id']) && !empty($postData['ss_id'])) ? $postData['ss_id'] : 'SS-4820226106006849';
        $postData['sign'] = $this->generateSignature($postData, $serverInfo['server_secret'])['sign'];
        $response = $this->http->post('https://21ds.cn/sms/send', $postData);
        return json_decode($response->body(), true);
    }
    public function getFileUrl($postData)
    {
        $postData['dev_key'] = (isset($postData['dev_key']) && !empty($postData['dev_key'])) ? $postData['dev_key'] : 'DEV-f3ed55c0-6f60-8303-eaf4-eec02a2008c9';
        $postData['file_url'] = is_array($postData['file_url']) ? implode(',', $postData['file_url']) : $postData['file_url'];
        $postData['file_id'] = isset($postData['file_id']) ? $postData['file_id'] : '';
        $postData['fs_id'] = $postData['fs_id'];
        $postData['remote_ip'] = (isset($postData['remote_ip']) && !empty($postData['remote_ip'])) ? $postData['remote_ip'] : '127.0.0.1';
        $serverInfo = $this->redisCache->getFileServer($postData['fs_id']);
        $postData['sign'] = $this->generateSignature($postData, $serverInfo['server_secret'])['sign'];
        $response = $this->http->post('https://21ds.cn/file/getFileUrl', $postData);
        return json_decode($response->body(), true);
    }
    function doSendPush($smsData, $server_secret = null,$uid = 0)
    {
        $apiUrl = 'https://21ds.cn/push/send';
        $postData['click_type_content'] = (isset($smsData['click_type_content']) && !empty($smsData['click_type_content'])) ? $smsData['click_type_content'] : json_encode([]);
        $postData['click_type'] = (isset($smsData['click_type']) && !empty($smsData['click_type'])) ? $smsData['click_type'] : '';
        $postData['msg_type'] = (isset($smsData['msg_type']) && !empty($smsData['msg_type'])) ? $smsData['msg_type'] : '';
        $postData['msg_content'] = (isset($smsData['msg_content']) && !empty($smsData['msg_content'])) ? $smsData['msg_content'] : '';
        $postData['atMobiles'] = (isset($smsData['atMobiles']) && !empty($smsData['atMobiles'])) ? $smsData['atMobiles'] : '';
        $postData['params_json'] = (isset($smsData['params_json']) && !empty($smsData['params_json'])) ? $smsData['params_json'] : '';
        $postData['template_data'] = (isset($smsData['template_data']) && !empty($smsData['template_data'])) ? $smsData['template_data'] : '';
        $postData['template_miniprogram'] = (isset($smsData['template_miniprogram']) && !empty($smsData['template_miniprogram'])) ? $smsData['template_miniprogram'] : '';
        $postData['template_url'] = (isset($smsData['template_url']) && !empty($smsData['template_url'])) ? $smsData['template_url'] : '';
        $postData['template_touser'] = (isset($smsData['template_touser']) && !empty($smsData['template_touser'])) ? $smsData['template_touser'] : '';
        $postData['template_id'] = (isset($smsData['template_id']) && !empty($smsData['template_id'])) ? $smsData['template_id'] : '';
        $postData['title'] = $smsData['title'];
        $postData['content'] = $smsData['content'];
        $postData['cid'] = (isset($smsData['cid']) && !empty($smsData['cid'])) ? $smsData['cid'] : '';
        $postData['dev_key'] = (isset($smsData['dev_key']) && !empty($smsData['dev_key'])) ? $smsData['dev_key'] : '';
        $redisCache = new RedisCache();
        if (!empty($uid)) {
            $userSetting = $redisCache->getUserSettingByUid($uid);
            $postData['dev_key'] = $userSetting['dev_key'];
        }
        $postData['ps_id'] = (isset($smsData['ps_id']) && !empty($smsData['ps_id'])) ? $smsData['ps_id'] : 'PS-4825470945110373';
        $postData['psl_id'] = (isset($smsData['psl_id']) && !empty($smsData['psl_id'])) ? $smsData['psl_id'] : '';
        $postData['platform'] = (isset($smsData['platform']) && !empty($smsData['platform'])) ? $smsData['platform'] : '';
        if (!empty($server_secret)) {
            $postData['sign'] = $this->generateSignature($postData, $server_secret)['sign'];
        }else{
            $pushServer = $redisCache->getPushServer($postData['ps_id']);
            $postData['sign'] = $this->generateSignature($postData, $pushServer['server_secret'])['sign'];
        }
        $response = $this->http->post($apiUrl, $postData);
        return json_decode($response->body(), true);
    }
    public function logPush($postData, $server_secret=null)
    {
        if (empty($server_secret)) {
            $server_secret = 'QnXDxYewdcwZHteCP57PJiSiXG7aSYbcE8ktyNMYPCRG3A5i8ESyBshZ8BPy3Wjb';
        }
        $postData['lsi_id'] = (isset($postData['lsi_id']) && !empty($postData['lsi_id'])) ? $postData['lsi_id'] : 'LSI-4839341746883385';
        $postData['sign'] = $this->generateSignature($postData, $server_secret)['sign'];
        $response = $this->http->post('https://21ds.cn/log/push', $postData);
        return json_decode($response->body(), true);
    }
    public function devSignGeneral($postData, $secret)
    {
        unset($postData['sign']);
        if (is_array($postData)) {
            foreach ($postData as $k => $v) {
                $Parameters[$k] = $v;
            }
            unset($postData, $k, $v);
            // 签名步骤一：按字典序排序参数
            ksort($Parameters);
            $buff = '';
            foreach ($Parameters as $k => $v) {
                $buff .= $k . $v;
            }
            unset($Parameters, $k, $v);
            $buff = $secret . $buff . $secret;
            $sign = strtoupper(md5($buff));
            unset($buff, $secret);
            return $sign;
        }
    }
    public function generateSignature($data, $secretKey)
    {
        unset($data['sign']);
        ksort($data);
        $queryString = http_build_query($data);
        $queryString .= $secretKey;
        $signature = hash('sha256', $queryString);
        return ['sign'=>$signature,'query'=> $queryString];
    }
    public function validateEmail($email)
    {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return true;
        } else {
            return false;
        }
    }
    public function validatePhoneNumber($phoneNumber)
    {
        // 定义手机号的正则表达式规则
        $pattern = '/^1[3-9]\d{9}$/';
        // 使用preg_match进行匹配，如果匹配成功返回true，否则返回false
        if (preg_match($pattern, $phoneNumber)) {
            return true;
        } else {
            return false;
        }
    }
    public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        list($tree, $map) = [[], []];
        foreach ($list as $item) $map[$item[$id]] = $item;
        foreach ($list as $item) if (isset($item[$pid]) && isset($map[$item[$pid]])) {
            $map[$item[$pid]][$son][] = &$map[$item[$id]];
        } else $tree[] = &$map[$item[$id]];
        unset($map,$list,$pid,$son,$id);
        return $tree;
    }
}
